package springboot.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import springboot.dao.UserDao;
import springboot.domain.User;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Optional;


@Controller
@Api(tags="用户模块的管理")
public class UserController {

    @Resource
    private UserDao userDao;

    @ResponseBody
    @GetMapping("/test")
    @ApiOperation(value="用于测试web环境有没有搭建好")
    public String getTest(){
        return "ok";
    }

    //这里的value是缓存的全局标识，key是键值对的键通过键来获取内容(要加一个#号)，
    // 有一个缺点就是没有过期时间，所以要在打包后在堆中开辟足够多的空间
    @ResponseBody
    @GetMapping("/getUser/{id}")
    @Cacheable(value = "user",key = "#id")//查询时加入缓存中，更新删除时删除缓存
    // key = "#id+'-'+#xxx+'-'+#xx" 将多个属性组合为一个key，引入到缓存中
    @ApiOperation(value = "获得指定id用户的信息")
    @ApiImplicitParam(name="id",value="用户的id",required=true,dataType = "Integer",paramType = "path")
    public User getUser(@PathVariable Integer id){
        Optional<User> optional = userDao.findById(id);
        if (optional.isPresent()){
            return optional.get();
        }
        return null;
    }
    @ResponseBody
    @GetMapping("/insertUser")
    @ApiOperation(value = "新增用户信息")
    @Transactional(propagation= Propagation.REQUIRED)//加入事务
    public User insertUser(@Valid User user){
        User userRet=userDao.saveAndFlush(user);
        return userRet;
    }

    @ResponseBody
    @GetMapping("/updateUser")
    @CacheEvict(value = "user",key = "#user.id")//更新时删除缓存 或者使用 @CachePut 来更新redis缓存
    @ApiOperation(value = "修改指定id用户的信息")
    @ApiImplicitParam(name="user",value = "用户的信息",dataType = "User")
    @Transactional(propagation= Propagation.REQUIRED)//加入事务
    public String updateUser(User user){//key = "#user.id"所以必须要有id
        if (user.getId()==null){//这边进入不了，因为是个demo，所以就不修改了
            return "this is update !!! insert failed!";//注意：这里传入的值如果没有id，则是新增
        }
        User save = userDao.save(user);
        return "ok";
    }

    @GetMapping("/delete/{id}")
    @CacheEvict(value = "user",key = "#id")
    public String deleteUser(@PathVariable Integer id) {

        userDao.deleteById(id);
        return "success";
    }

}
